package com.devplatform.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.devplatform.pojo.Categories;
import com.devplatform.pojo.article.Article;
import com.devplatform.pojo.article.ArticleInteractions;
import com.devplatform.pojo.article.ReadHistory;
import com.devplatform.pojo.dto.ArticleDraftDto;
import com.devplatform.pojo.dto.ArticleDto;
import com.devplatform.pojo.dto.ArticlePublishDto;
import com.devplatform.pojo.vo.DataVo;
import com.devplatform.pojo.vo.SearchVo;
import com.devplatform.service.CategoriesService;
import com.devplatform.service.article.ArticleInteractionsService;
import com.devplatform.service.article.ArticleService;
import com.devplatform.service.article.ReadHistoryService;
import com.devplatform.service.impl.article.ArticleDtoService;
import com.devplatform.util.UserContextHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/article")
@RequiredArgsConstructor
public class ArticleController {
    private final ArticleService articleService;
    private final CategoriesService categoriesService;
    private final ArticleDtoService articleDtoService;
    private final ReadHistoryService readHistoryService;
    private final ArticleInteractionsService atInteractionsService;

    @GetMapping("/getList/{articleId}")
    //根据前端获取的信息获取文章id
    public DataVo getArticle(@PathVariable Long articleId) {
        Long authorId = articleService.getAuthorIdByArticleId(articleId);
        ArticleDto articleDetails = articleDtoService.getArticleDetails(authorId, articleId);
        if (articleDetails == null) {
            return DataVo.error("文章不存在");
        }
        //添加浏览量
        ArticleInteractions atInteractions = atInteractionsService.getOne(
                new LambdaQueryWrapper<ArticleInteractions>()
                        .eq(ArticleInteractions::getArticleId, articleId)
        );
        if (atInteractions == null) {
            atInteractions = new ArticleInteractions();
            atInteractions.setArticleId(articleId);
            atInteractions.setViewCount(1);
            atInteractionsService.save(atInteractions);
        } else {
            atInteractions.setViewCount(atInteractions.getViewCount() + 1);
            atInteractionsService.updateById(atInteractions);
        }

        //添加历史记录
        if (UserContextHolder.getUserId() == null) {
            //代表无token访问，不添加历史记录
            return DataVo.ok(articleDetails);
        }
        ReadHistory readHistory = new ReadHistory();
        readHistory.setArticleId(articleId);
        readHistory.setUserId(UserContextHolder.getUserId());
        readHistory.setTitle(articleDetails.getTitle());
        readHistoryService.save(readHistory);

        return DataVo.ok(articleDetails);
    }

    //分页查询模块列表
    @GetMapping("/getCategoryList")
    public DataVo getCategoryList(@RequestParam(defaultValue = "1") int page,
                                  @RequestParam(defaultValue = "10") int size) {
        IPage<Categories> categoriesIPage = new Page<>(page, size);
        categoriesService.page(categoriesIPage);
        return DataVo.ok(categoriesIPage);
    }


    // 文章列表分页查询（支持标题、作者、板块筛选）
    @GetMapping("/getList")
    public DataVo getList(
            @RequestParam(defaultValue = "1") Integer currentPage,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String categoryName,
            @RequestParam(required = false) Integer statusId
    ) {
        Page<ArticleDto> articlePage = new PageDTO<>(currentPage, pageSize);
        Map<String, Object> params = new HashMap<>();
        params.put("title", title);
        params.put("username", username);
        params.put("categoryName", categoryName);
        if (statusId != null) {
            params.put("statusId", statusId);
        }
        Page<ArticleDto> resultPage = articleDtoService.searchArticles(articlePage, params);
        return DataVo.ok(resultPage);
    }

    //2. 热门文章分页查询
    @PostMapping("/getHotList")
    public DataVo getHotList(@RequestBody SearchVo searchVo) {
        Page<ArticleDto> hotPage = new PageDTO<>(searchVo.getCurrentPage(), searchVo.getPageSize());
        QueryWrapper<ArticleDto> queryWrapper = new QueryWrapper<>();

        // 只查询状态正常的文章
        queryWrapper.eq("a.status_id", 1);
        queryWrapper.eq("a.is_deleted", 0);
        queryWrapper.in(!searchVo.getCategories().isEmpty(), "c.category_name", searchVo.getCategories());
        queryWrapper.and(
                StringUtils.hasText(searchVo.getKeyword()),
                qw -> {
                    qw.like("a.title", searchVo.getKeyword())
                            .or()
                            .like("a.summary", searchVo.getKeyword())
                            .or()
                            .like("u.username", searchVo.getKeyword());
                });

        Page<ArticleDto> resultPage = articleDtoService.recommendHotArticles(hotPage, queryWrapper);
        return DataVo.ok(resultPage);
    }

    //单篇文章详情查询
    @GetMapping("/getDetail")
    public DataVo getDetail(
            @RequestParam(defaultValue = "1", name = "currentPage") Integer pageName,
            @RequestParam(defaultValue = "1", name = "pageSize") Integer pageSize,
            @RequestParam(required = false, name = "articleId") Integer articleId
    ) {
        Page<ArticleDto> detailPage = new PageDTO<>(pageName, pageSize);
        Map<String, Object> params = new HashMap<>();
        params.put("articleId", articleId);
        Page<ArticleDto> resultPage = articleDtoService.filterArticles(detailPage, params);
        if (resultPage.getRecords().isEmpty()) {
            return DataVo.error();
        }
        return DataVo.ok(resultPage);
    }

    //热度前100条 可以按板块
//    @GetMapping("/top100")
//    public DataVo getHotTop100Articles(
//            @RequestParam(required = false, name = "categoryName") String categoryName
//    ) {
//        List<ArticleDto> top100List = articleDtoService.getHotTop100Articles(categoryName);
//        return DataVo.ok(top100List);
//    }

    //查看历史记录
    @GetMapping("/readeHistory")
    public DataVo<List<ReadHistory>> getReadeHistory(@RequestParam String title) {
        Long userId = UserContextHolder.getUserId();
        LambdaQueryWrapper<ReadHistory> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(ReadHistory::getUserId, userId);
        wrapper.orderByDesc(ReadHistory::getReadTime);
        wrapper.like(StringUtils.hasText(title), ReadHistory::getTitle, title);

        List<ReadHistory> list = readHistoryService.list(wrapper);
        return DataVo.ok(list);
    }

    //删除历史记录
    @DeleteMapping("/readeHistory")
    public DataVo<String> deleteReadeHistory() {
        Long userId = UserContextHolder.getUserId();
        LambdaQueryWrapper<ReadHistory> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(ReadHistory::getUserId, userId);
        if (readHistoryService.remove(wrapper)) {
            return DataVo.ok("删除成功");
        } else {
            return DataVo.error("删除失败");
        }
    }

    //新增文章草稿/创建，编辑文章
    @PostMapping("/draft")
    public DataVo saveDraft(@RequestBody ArticlePublishDto dto) {
        return articleService.saveDraft(dto);
    }

    // 发布文章接口
    @PostMapping("/publish/{articleId}")
    public DataVo publishArticle(@PathVariable Long articleId) {
        return articleService.publish(articleId);
    }
    //获取草稿详情
    @GetMapping("/draft/{articleId}")
    public DataVo getArticleDetail(@PathVariable Long articleId) {
        Long authorId = UserContextHolder.getUserId();
        return articleService.getArticleDetail(articleId, authorId);
    }

    //删除草稿
    @DeleteMapping("/draft/{articleId}")
    public DataVo deleteDraft(@PathVariable Long articleId) {
        Long authorId = UserContextHolder.getUserId();
        return articleService.deleteDraft(articleId, authorId);
    }

    //获取草稿箱列表
    @GetMapping("/drafts")
    public DataVo getDraftList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        Long authorId = UserContextHolder.getUserId();
        IPage<ArticleDraftDto> dtoIPage = new Page<>(page, size);
        return articleService.getDraftList(authorId, dtoIPage);
    }

    //获取板块表
    @GetMapping("/getCategories")
    public DataVo<List<Categories>> getAllCategories() {
        List<Categories> categories = articleService.getAllCategories();
        return DataVo.ok(categories);
    }


    @GetMapping("/getUserByArticleId")
    public DataVo getUserByArticleId(
            @RequestParam String articleId
    ) {
        try {
            if (articleId == null || articleId.trim().isEmpty()) {
                return DataVo.error("文章ID不能为空");
            }
            Long articleIdLong;
            try {
                articleIdLong = Long.valueOf(articleId);
            } catch (NumberFormatException e) {
                return DataVo.error("文章ID格式错误：" + articleId);
            }
            Article article = articleService.getById(articleIdLong);
            if (article == null) {
                return DataVo.error("文章不存在：" + articleId);
            }
            Long authorId = article.getAuthorId();
            if (authorId == null) {
                return DataVo.error("文章未关联作者：" + articleId);
            }
            return DataVo.ok(Map.of("userId", authorId.toString()));

        } catch (Exception e) {
            return DataVo.error("查询失败：" + e.getMessage());
        }
    }
}
